<?php

namespace App\Http\Middleware;

use App\Sys\Models\SysAppModel;
use App\User\Facades\UserInfoFacade;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use App\Exceptions\ApiException;

class MiniprogAuthenticate
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory $auth
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     * @throws ApiException
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if(empty($request->user())){
            throw new ApiException(401);
        }
        $user = $request->user();
        if(empty($user['is_super'])) {
            $noAuth = true;
            if(!empty($user['bind_app'])) {
                foreach ($user['bind_app'] as $bind) {
                    if($bind['code'] === SysAppModel::APP_CODE_MINIPROG_FRONT) {
                        $noAuth = false;
                        break;
                    }
                }
            }
            if($noAuth) {
                throw new ApiException('common.app_not_auth', '应用未授权！');
            }
        }
        $userId = $user['id'];
        $token = $request->header('token');
        //如果不是最近登录的token
        if (config('app.login_singleton') && !UserInfoFacade::isLastToken($userId, $token)) {
            UserInfoFacade::logout($token);
            throw new ApiException(10008);
        }
        return $next($request);
    }
}
